<?php
namespace StarCloud\Services;

use StarCloud\Library\CustomerException;
use StarCloud\Library\Tool;

class SmsService extends BaseService
{
    const SMS_SIGN_NAME = '抖盟';

    const SMS_TEMPLATE_CODE = 'SMS_172560048'; // 登陆验证码模版

    const SMS_CACHE_EXPIRE_TIME = 300;

    public static function sendCode($phone, $signName, $templateCode, $code = '')
    {
        if (empty($code)) {
            $code = Tool::smsCode();
        }
        
        $result = self::getSmsClient()->sendCode($phone, $signName, $templateCode, ['code' => $code]);

        if (isset($result['Code']) && $result['Code'] == 'OK') {
            self::getRedis()->set(self::createVerifySmsCodeKey($phone), $code, self::SMS_CACHE_EXPIRE_TIME);

            return true;
        } else {
            throw new CustomerException(20101);
        }
    }

    public static function verifyCode($phone, $code)
    {
        if (ENVIRONMENT == 'development') {
            return true;
        }
        $result = rtrim(self::getRedis()->get(self::createVerifySmsCodeKey($phone))) == rtrim($code);

        $result && self::getRedis()->del(self::createVerifySmsCodeKey($phone));

        return $result;
    }

    protected static function createVerifySmsCodeKey($phone)
    {
        return 'start_cloud_sms_' . $phone;
    }
}
